var express = require('express');
var router = express.Router();
var fetch = require('node-fetch');
const userService = require("../service/usersService");
const { sha256, secretKey } = require('../utils');
const jwt = require("jsonwebtoken");
const { base64_decode } = require('../utils');
const { v4: uuidv4 } = require('uuid');
const https = require("https");
const httpsAgent = new https.Agent({ rejectUnauthorized: false });

const APP_ID = "wxf594be5aa3f79798";
const SECRET = "e7e387623d59683e08d7683d6e1dd45c";

//登录
router.post('/login', async function (req, res, next) {
  let { username, pwd } = req.body;
  let data = await userService.login({ username, pwd: sha256(pwd) });
  // let data = await userService.login({ username, pwd });
  console.log("管理员", data);
  if (data.length > 0) {
    let token = jwt.sign({ data: data[0] }, secretKey);
    if (data[0].privilege == "1") {
      // req.session.user = data[0];
      res.send({
        token,
        state: 1,
        str: "登陆成功"
      });
    } else {
      res.send({
        token,
        state: 3,
        str: "您不是管理员"
      });
    }
  } else {
    res.send({
      state: 0,
      str: "登陆失败"
    });
  }
});

router.get('/wxLogin', async function (req, res, next) {
  console.log(req.query);
  let code = req.query.code;
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
  try {
    let fetchResult = await fetch(url, {
      agent: httpsAgent
    });
    let data = await fetchResult.json();
    console.log('data', url, data)
    if (!data.errcode) {
      let user = await userService.userFind(data.openid);
      if (Object.keys(user).length > 0) {
        res.send(user);
      } else {
        let newUser = await userService.insert({ username: data.openid, pwd: '' });
        res.send(newUser);
      }
    } else {
      res.send({});
    }
  } catch (e) {
    console.log("error:", e);
    res.send({});
  }
})

router.post('/wxDetail', async function (req, res, next) {
  let { nickname, image } = req.body;
  if (image) {
    let strUUID = uuidv4();
    base64_decode(image, "./public/image/" + strUUID + ".jpeg");

    res.send({ nickname, image: strUUID + ".jpeg" });
    return;
  }
  res.send({});
})

//添加用户
router.post('/add', async function (req, res, next) {
  let { username, pwd, phone, email, privilege, headImg } = req.body;
  if (username == "" || pwd == "") {
    res.send({ data: "账号或密码不能为空" });
    return
  }
  let data = await userService.insert({ username, pwd: sha256(pwd), phone, email, privilege, headImg });
  // let data = await userService.insert({ username, pwd  });
  res.send({ data });
});

//删除用户信息
router.delete('/:id', async function (req, res) {
  let { id } = req.params;
  let data = await userService.remove({ _id: id });
  res.send({ data });
});

//修改用户信息
router.put('/:id', async function (req, res) {
  let { id } = req.params;
  let newData = req.body;
  if (newData.pwd) {
    newData.pwd = sha256(newData.pwd);
  }
  let data = await userService.upData(id, newData);
  res.send({ data });
});

//搜索用户信息
router.get('/', async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchObj = {};
  if (type) {
    if (type == "phone") {
      searchObj[type] = value;
    } else {
      searchObj[type] = { $regex: value };
    }
  };
  let data = await userService.search(searchObj, { current: current || 1, pageSize: pageSize || 10 });
  res.send({ data });
});

//查询用户是否存在
router.post("/username", async function (req, res, next) {
  let { username } = req.body;
  let data = await userService.userFind(username);
  if (data.length > 0) {
    res.send({
      state: 1,
      str: "已注册"
    })
  } else {
    res.send({
      state: 0,
      str: "未注册"
    })
  }
})

// 通过id查找
router.get('/:id', async function (req, res) {
  let { id } = req.params;
  let data = await userService.findById(id);
  res.send({ data });
});

module.exports = router;
